package com.dcits.electronic_account.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: CZJ
 * @Date： 2022/6/26
 */

@Component
@Log4j2
public class JwtUtils {

    // 过期时间、密钥
    private static long expire = 2 * 60 * 60 * 1000;
    private static String secret = "HSyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";

    /**
     * @func 生成token
     * @param account
     * @return
     */
    public String generateToken(String account) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + expire);
        return Jwts.builder().setHeaderParam("type", "JWT").setSubject(account).setIssuedAt(now)
                .setExpiration(expireDate).signWith(
                        SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * @func 解析token
     * @param token
     * @return
     */
    public Claims getClaimsByToken(String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.info("validate is token error");
            return null;
        }
    }

    /**
     * @func 判断token是否过期
     * @param expiration
     * @return
     */
    public boolean isTokenExpired(Date expiration){
        return expiration.before(new Date());
    }
}
